package com.aura.springbook.controller;

import com.aura.springbook.common.R;
import com.aura.springbook.common.util.PageUtil;
import com.aura.springbook.common.util.ResponseUtil;
import com.aura.springbook.model.Book;
import com.aura.springbook.model.BookCategory;
import com.aura.springbook.model.vo.BookVO;
import com.aura.springbook.service.BookCategoryService;
import com.aura.springbook.service.BookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/books")
@Tag(name = "图书接口", description = "图书相关操作接口")
public class BookController {
    
    private static final Logger logger = LoggerFactory.getLogger(BookController.class);
    
    @Autowired
    private BookService bookService;
    
    @Autowired
    private BookCategoryService bookCategoryService;
    
    /**
     * 查询所有图书（分页）
     */
    @GetMapping
    @Operation(summary = "查询所有图书", description = "分页查询所有图书")
    @Parameters({
        @Parameter(name = "page", description = "页码，默认为1"),
        @Parameter(name = "size", description = "每页大小，默认为10")
    })
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "400", description = "分页参数不合法")
    })
    public R<IPage<Book>> getBooksByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        logger.debug("收到查询所有图书请求, 页码: {}, 每页大小: {}", page, size);
        
        // 验证并处理分页参数
        PageUtil.ValidationResult result = PageUtil.validateAndProcess(page, size);
        if (!result.isValid()) {
            logger.warn("查询所有图书失败, 分页参数不合法, 页码: {}, 每页大小: {}", page, size);
            return (R<IPage<Book>>) result.getErrorResponse();
        }
        
        IPage<Book> books = bookService.getBooksByPage(result.getPage(), result.getSize());
        logger.debug("查询所有图书成功, 总记录数: {}", books.getTotal());
        return ResponseUtil.success(books);
    }
    
    /**
     * 按分类查询图书（分页）
     */
    @GetMapping("/category/{cid}")
    @Operation(summary = "按分类查询图书", description = "根据分类ID分页查询图书")
    @Parameters({
        @Parameter(name = "cid", description = "分类ID", required = true),
        @Parameter(name = "page", description = "页码，默认为1"),
        @Parameter(name = "size", description = "每页大小，默认为10")
    })
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "400", description = "分页参数不合法")
    })
    public R<IPage<Book>> getBooksByCategory(
            @PathVariable Long cid,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        logger.debug("收到按分类查询图书请求, 分类ID: {}, 页码: {}, 每页大小: {}", cid, page, size);
        
        // 验证并处理分页参数
        PageUtil.ValidationResult result = PageUtil.validateAndProcess(page, size);
        if (!result.isValid()) {
            logger.warn("按分类查询图书失败, 分页参数不合法, 分类ID: {}, 页码: {}, 每页大小: {}", cid, page, size);
            return (R<IPage<Book>>) result.getErrorResponse();
        }
        
        IPage<Book> books = bookService.getBooksByCategory(cid, result.getPage(), result.getSize());
        logger.debug("按分类查询图书成功, 分类ID: {}, 总记录数: {}", cid, books.getTotal());
        return ResponseUtil.success(books);
    }
    
    /**
     * 按关键词搜索图书
     */
    @GetMapping("/search")
    @Operation(summary = "搜索图书", description = "根据关键词搜索图书")
    @Parameters({
        @Parameter(name = "keyword", description = "搜索关键词", required = true),
        @Parameter(name = "page", description = "页码，默认为1"),
        @Parameter(name = "size", description = "每页大小，默认为10")
    })
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "400", description = "分页参数不合法")
    })
    public R<IPage<Book>> searchBooks(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        logger.debug("收到搜索图书请求, 关键词: {}, 页码: {}, 每页大小: {}", keyword, page, size);
        
        // 验证并处理分页参数
        PageUtil.ValidationResult result = PageUtil.validateAndProcess(page, size);
        if (!result.isValid()) {
            logger.warn("搜索图书失败, 分页参数不合法, 关键词: {}, 页码: {}, 每页大小: {}", keyword, page, size);
            return (R<IPage<Book>>) result.getErrorResponse();
        }
        
        IPage<Book> books = bookService.searchBooks(keyword, result.getPage(), result.getSize());
        logger.debug("搜索图书成功, 关键词: {}, 总记录数: {}", keyword, books.getTotal());
        return ResponseUtil.success(books);
    }
    
    /**
     * 查询单本图书详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询图书详情", description = "根据图书ID查询图书详细信息")
    @Parameter(name = "id", description = "图书ID", required = true)
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "图书不存在")
    })
    public R<BookVO> getBookDetail(@PathVariable Long id) {
        logger.debug("收到查询图书详情请求, 图书ID: {}", id);
        
        Book book = bookService.getBookDetail(id);
        if (book != null) {
            // 转换为VO对象，包含分类名称
            BookVO bookVO = new BookVO();
            BeanUtils.copyProperties(book, bookVO);
            
            // 获取分类名称
            BookCategory category = bookCategoryService.getCategoryById(book.getCategoryId());
            if (category != null) {
                bookVO.setCategoryName(category.getName());
            }
            
            logger.debug("查询图书详情成功, 图书ID: {}, 图书标题: {}", id, book.getTitle());
            return ResponseUtil.success(bookVO);
        } else {
            logger.warn("查询图书详情失败, 图书ID: {} 不存在", id);
            return ResponseUtil.notFound();
        }
    }
}